#include <linux/err.h>
#include <plat/mcspi.h>
#include <asm/uaccess.h>
#include <linux/interrupt.h>
#include <linux/input.h>
#include <linux/spi/spi.h>
#include "ads7870-spi.h"
#include <linux/module.h>

#define MODULE_DEBUG 0
/* 
 * Pointer to SPI Device 
 */
static struct spi_device *psoc_spi_device;

/* 
 * SPI Configuration Structure
 * Used when creating a new SPI Device
 */
static struct omap2_mcspi_device_config psoc_mcspi_config = {
  .turbo_mode	        = 0,
  .single_channel	= 1,  /* 0: slave, 1: master */
};

struct spi_board_info omap3devkit8000_spi_board_info[] = {
  {
    .modalias		= "psoc",
    .bus_num		= 1,
    .chip_select	= 0,
    .max_speed_hz	= 1000000,
    .controller_data	= &psoc_mcspi_config,
    .mode               = SPI_MODE_3, // Clock polarity
  },

};
struct spi_result psoc_read()
{
  struct spi_result result;
  result.fejl = psoc_read_once(psoc_spi_device);
  result.temperatur = psoc_read_once(psoc_spi_device);
  result.batteri = psoc_read_once(psoc_spi_device);
  result.stroem = psoc_read_once(psoc_spi_device);
  return result;
}
int psoc_write(struct spi_device *spi)
{
  struct spi_transfer t[1];
  struct spi_message m;
  u16 cmd = 0xAAAA;
  memset(&t, 0, sizeof(t));
  
  spi_message_init(&m);
  m.spi = spi;
  t[0].tx_buf = &cmd;
  t[0].rx_buf = NULL;
  t[0].len = 2;
  spi_message_add_tail(&t[0], &m);
  return spi_sync(m.spi,&m);
}
u16 psoc_read_once(struct spi_device *spi)
{

  u16 temp;
  struct spi_transfer t[1];
  struct spi_message m;
  memset(&t, 0, sizeof(t));
  
  spi_message_init(&m);
  m.spi = spi;
  t[0].tx_buf = NULL;
  t[0].rx_buf = &temp;
  t[0].len = 2;
  spi_message_add_tail(&t[0], &m);
  spi_sync(m.spi,&m);
  return temp;  

}

static int __devinit psoc_spi_probe(struct spi_device *spi)
{
  psoc_spi_device->bits_per_word = 16;  
  spi_setup(psoc_spi_device);

  return 0;
}

static int __devexit psoc_remove(struct spi_device* spi)
{
  return 0;
}

static struct spi_driver psoc_spi_driver = {
  .driver = {
    .name = "psoc",
    .bus = &spi_bus_type,
    .owner = THIS_MODULE,
  },
  .probe = psoc_spi_probe,
  .remove = __devexit_p(psoc_remove),
};


/*
 * Init / Exit routines called from 
 * character driver. Init registers the spi driver
 * and the spi host probes the device upon this.
 * Exit unregisters the driver and the spi host
 * calls _remove upon this
 */

int psoc_spi_init()
{
  int err, bus_num;
  struct spi_master *psoc_spi_master;

  bus_num = omap3devkit8000_spi_board_info->bus_num;
  psoc_spi_master = spi_busnum_to_master(bus_num);
  psoc_spi_device = spi_new_device(psoc_spi_master,
				      omap3devkit8000_spi_board_info);

  if((err=spi_register_driver(&psoc_spi_driver))<0)
    printk (KERN_ALERT "Error %d registering the ads7870 SPI driver\n", err);

  return err;
}

int psoc_spi_exit()
{
  /*
   * Un-register spi driver and device
   * Spi host calls _remove upon this
   */
  spi_unregister_driver(&psoc_spi_driver); 
  spi_unregister_device(psoc_spi_device);

  return 0;
}


